package com.qiguliuxing.dts.wx.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.aliyuncs.utils.StringUtils;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.db.dao.DtsGoodsProductMapper;
import com.qiguliuxing.dts.db.domain.DtsGoodsProduct;
import com.qiguliuxing.dts.db.domain.DtsGoodsProductExample;
import com.qiguliuxing.dts.service.base.DtsGoodsProductService;
import com.qiguliuxing.dts.service.base.DtsGoodsService;
import com.qiguliuxing.dts.service.base.DtsTopicService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsGoods;
import com.qiguliuxing.dts.db.domain.DtsTopic;

/**
 * 专题服务
 */
@RestController
@RequestMapping("/wx/topic")
@Validated
@Api(tags = "专题服务")
public class WxTopicController {
	private static final Logger logger = LoggerFactory.getLogger(WxTopicController.class);

	@Autowired
	private DtsTopicService topicService;
	@Autowired
	private DtsGoodsService goodsService;

	@Autowired
	private DtsGoodsProductMapper dtsGoodsProductMapper;

	/**
	 * 专题列表
	 *
	 * @param page
	 *            分页页数
	 * @param size
	 *            分页大小
	 * @return 专题列表
	 */
	@GetMapping("list")
	@ApiOperation(value = "专题列表")
	@WebLog(description = "专题列表",excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer size,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsTopic> topicList = topicService.queryList(page, size, sort, order);
		int total = topicService.queryTotal();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("data", topicList);
		data.put("count", total);
		return ResponseUtils.ok(data);
	}

	/**
	 * 专题详情
	 *
	 * @param id
	 *            专题ID
	 * @return 专题详情
	 */
	@GetMapping("detail")
	@ApiOperation(value = "专题详情")
	@WebLog(description = "专题详情")
	public Object detail(@ApiParam(value = "专题ID")@NotNull Integer id) {
		Map<String, Object> data = new HashMap<>();
		DtsTopic topic = topicService.findByIdAll(id);
		LocalDateTime addTime = topic.getAddTime();
		LocalDateTime endTime = topic.getEndTime();
		if(LocalDateTime.now().isBefore(addTime)){
			topic.setState((byte) 1);
		}
		if(LocalDateTime.now().isAfter(addTime)&&LocalDateTime.now().isBefore(endTime)) {
			topic.setState((byte) 2);
		}
		if(LocalDateTime.now().isAfter(endTime)){
			topic.setState((byte) 3);
		}
		data.put("topic", topic);
		List<DtsGoods> goods = new ArrayList<>();
		if(null==topic){
			return ResponseUtils.fail();
		}
		for (String idOrSn : topic.getGoods()) {
			try {
				Long sn;
				int sales=0;
				if(idOrSn.contains("-")){
					sn=Long.parseLong(idOrSn.split("-")[0]);
					sales=Integer.valueOf(idOrSn.split("-")[1]);
				}else{
					sn=Long.parseLong(idOrSn);
				}
				DtsGoods good = null;
				good = goodsService.findById(sn.intValue());
				if (null != good) {
					good.setSales(sales+(good.getSales()==null?0:good.getSales().intValue()));
					goods.add(good);
					DtsGoodsProductExample example = new DtsGoodsProductExample();
					example.or().andGoodsIdEqualTo(good.getId()).andDeletedEqualTo(false);
					List<DtsGoodsProduct> list=dtsGoodsProductMapper.selectByExample(example);
					good.setProductList(list);
				}
			} catch (Exception e) {
				logger.info("获取专题详情,根据配置的商品id或sn获取商品详情出错:{}", e.getMessage());
				e.printStackTrace();
			}
		}

		data.put("goods", goods);
		return ResponseUtils.ok(data);
	}

	/**
	 * 相关专题
	 *
	 * @param id
	 *            专题ID
	 * @return 相关专题
	 */
	@GetMapping("related")
	@ApiOperation(value = "相关专题")
	@WebLog(description = "相关专题")
	public Object related(@ApiParam(value = "专题ID") @NotNull Integer id) {
		List<DtsTopic> topicRelatedList = topicService.queryRelatedList(id, 0, 6);
		return ResponseUtils.ok(topicRelatedList);
	}
}
